#pragma once
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

#include "Article.h"

using namespace std;

class ArticleRegister
{
private:
	string newspaper;
	vector<Article> v;
public:

	ArticleRegister() : newspaper("N/A") { }

	ArticleRegister(string newspaper)
	{
		this->newspaper = newspaper;
	}

	~ArticleRegister() { }

	void setNewspaper(string newspaper){ this->newspaper = newspaper; }
	string getNewspaper(){ return newspaper; }

	string List()
	{
		ostringstream oss;
		oss << newspaper << endl;
		for (auto a : v)
		{
			oss << a << endl;
		}
		return oss.str();
	}

	void Add(Article a)
	{
		v.push_back(a);
	}

	void WriteToFile(string filename)
	{
		ofstream fout;
		try
		{
			fout.open(filename);
			fout << "ArticleRegister=(";
			fout << newspaper << ")" << endl;
			for (auto a : v)
			{
				fout << "Article=" << a << endl;
			}
		}
		catch (exception e)
		{
			cout << e.what() << endl;
		}
		fout.close();
	}

	void ReadFromFile(string filename)
	{
		string str, row;
		ifstream fin;
		v.clear();
		try
		{
			fin.open(filename);
			while (getline(fin, row))
			{
				istringstream iss(row);
				getline(iss, str, '=');
				if (str.compare("ArticleRegister") == 0)
				{
					getline(iss, str, '(');
					getline(iss, newspaper, ')');
				}
				else if (str.compare("Article") == 0)
				{
					Article a;
					iss >> a;
					if (a.getId() != -1)
					{
						v.push_back(a);
					}
				}
			}//end while
		}
		catch (exception e)
		{
			cout << e.what() << endl;
		}
		fin.close();
	}

	vector<string> SearchTitle(string searchTerm)
	{
		vector<string> vec;
		for (auto a : v)
		{
			string str;
			istringstream iss(a.getTitle());
			while (getline(iss, str, ' '))
			{
				if (str.compare(searchTerm) == 0)
				{
					ostringstream oss;
					oss << newspaper << ": " << a << endl;
					vec.push_back(oss.str());
				}
			}
		}
		return vec;
	}

	vector<string> SearchKeyword(string keyword)
	{
		vector<string> vec;
		for (auto a : v)
		{
			if (a.getKeyword().compare(keyword) == 0)
			{
				ostringstream oss;
				oss << newspaper << ": " << a << endl;
				vec.push_back(oss.str());
			}
		}
		return vec;
	}
};

